﻿using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Collections;
using System.Drawing;
using System.Data.SqlClient;
using AjaxControlToolkit;
public partial class Main_Inventory_EditPurchaseOrder : System.Web.UI.Page
{
    //for global variable and the List
    #region
    Datautility DU = new Datautility();
    CommonLog ComLog = new CommonLog();
    //PageId = "407";//This is the page id for the ItemMaster
    string strsql = "";
    string TempPoMainData = "";
    string PODetails = "";
    string ip = "";
    string Body = "";
    int ControlCounter = 5;
    string POID = "";
    List<string> LstList;
    List<string> LstQty;
    List<string> LstItemName;
    List<string> LstAutoExtName;
    List<string> LstUnit;
    List<string> LstMpn;    
    List<string> LstTaxRate;
    List<string> LstRateExcTax;
    List<string> LstAmountPayable;  
    #endregion
    //For the Webservice of the ItemName and the ItemCode
    #region
    [System.Web.Script.Services.ScriptMethod()]
    [System.Web.Services.WebMethod]
    public static List<string> GetItemName(string prefixText)
    {
        Datautility db = new Datautility();
        DataTable dt = db.getdata("select top 8 ITMCODE,ITMDESC,ITMID from IVR_ITEM where ITMCODE like '%" + prefixText + "%' or ITMDESC like '%" + prefixText + "%'");
        List<string> ItemName = new List<string>();
        List<int> ItemId = new List<int>();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ItemName.Add(Convert.ToString(dt.Rows[i]["ITMDESC"]) + "\\" + dt.Rows[i]["ITMCODE"].ToString());
        }
        return ItemName;
    }
    protected void txtItem_TextChanged(object sender, EventArgs e)
    {
        TextBox txt = (TextBox)sender;
        string txtid = txt.ID.ToString().Substring(7);
        int rowIndex = Convert.ToInt32(txtid.ToString());

        TextBox txtUnit = (TextBox)tblItem.Rows[rowIndex].FindControl("txtUnit" + rowIndex.ToString());
        TextBox txtQty = (TextBox)tblItem.Rows[rowIndex].FindControl("txtQty" + rowIndex.ToString());
        TextBox txtRateExcTax = (TextBox)tblItem.Rows[rowIndex].FindControl("txtRateExcTax" + rowIndex.ToString());
        TextBox txtAmountPayable = (TextBox)tblItem.Rows[rowIndex].FindControl("txtAmountPayable" + rowIndex.ToString());
        DropDownList DDLMPNNo = (DropDownList)tblItem.Rows[rowIndex].FindControl("ddlmpn" + rowIndex.ToString());

        if (txt.Text != "")
        {
            if (txt.Text.Contains("\\"))
            {
                string[] itemname = txt.Text.Split('\\');
                string sql = "select UOMSYMBOL from IVR_UOM inner join IVR_ITEM on IVR_UOM.UOMID=IVR_ITEM.PRIMARY_UOMID where IVR_ITEM.ITMCODE='" + itemname[1] + "'";
                DataTable DT = DU.getdata(sql);
                if (DT.Rows.Count > 0)
                {
                    txtUnit.Text = DT.Rows[0][0].ToString();
                    //ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "duplicatetext(" + txtid + ");", true);
                    string SqlMPN = "Select ID,MPNCODE from IVR_ITEM_MPN inner join IVR_ITEM on IVR_ITEM.ITMID=IVR_ITEM_MPN.ITEMID where IVR_ITEM.ITMCODE='" + itemname[1] + "'";
                    DataTable Dtmpn = DU.getdata(SqlMPN);
                    if (Dtmpn.Rows.Count > 0)
                    {
                        DDLMPNNo.DataSource = Dtmpn;
                        DDLMPNNo.DataTextField = "MPNCODE";
                        DDLMPNNo.DataValueField = "ID";
                        DDLMPNNo.DataBind();
                        DDLMPNNo.Items.Insert(0, new ListItem(" ", "0"));
                    }
                    else
                    {
                        DDLMPNNo.Items.Clear();
                    }
                    txt.BackColor = System.Drawing.Color.Red;
                    DDLMPNNo.BackColor = System.Drawing.Color.Red;
                    txtQty.BackColor = System.Drawing.Color.Red;
                    txtRateExcTax.BackColor = System.Drawing.Color.Red;
                }
            }
            else
            {
                txt.Text = ""; txtUnit.Text = "";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "removetext(" + rowIndex + ");", true);
                //Bind_VATCST();
            }
        }
        else
        {
            txtRateExcTax.Text = "";
            txtQty.Text = "";
            txtUnit.Text = "";
            txtAmountPayable.Text = "";
            //ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "calcQty(); calcAmt();", true);
        }
    }      
    #endregion
    //Addrow for the Item
    #region
    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);        
        LstList = (List<string>)ViewState["LstList"];
        LstItemName = (List<string>)ViewState["LstItemName"];
        LstAutoExtName = (List<string>)ViewState["LstAutoExtName"];
        LstQty = (List<string>)ViewState["LstQty"];
        LstMpn = (List<String>)ViewState["LstMpn"];
        LstUnit = (List<string>)ViewState["LstUnit"];        
        LstTaxRate = (List<string>)ViewState["LstTaxRate"];
        LstRateExcTax = (List<string>)ViewState["LstRateExcTax"];
        LstAmountPayable = (List<string>)ViewState["LstAmountPayable"];
        if (LstList != null)
        {
            int count = Convert.ToInt32(LstList.Count.ToString());
            for (int i = 0; i < count; i++)
            {
                ControlCounter++;
                Label lbl = new Label();
                lbl.ID = LstList[i].ToString();
                lbl.Text = ControlCounter.ToString();

                HtmlTableRow htrow = new HtmlTableRow();
                htrow.ID = "htrow" + ControlCounter.ToString();

                HtmlTableCell htcell1 = new HtmlTableCell();
                htcell1.ID = "htcell1" + ControlCounter.ToString();
                htcell1.VAlign = "Top";
                htcell1.Width = "35%";
                TextBox txtItem = new TextBox();
                txtItem.ID = LstItemName[i].ToString();
                txtItem.Width = Unit.Percentage(99);
                txtItem.AutoPostBack = true;
                txtItem.CssClass = "input";
                txtItem.Attributes.Add("onPaste", "return false;");
                //txtItem.Attributes.Add("onchange", "duplicaterow(this.id);");
                txtItem.TextChanged += new EventHandler(txtItem_TextChanged);
                htcell1.Controls.Add(txtItem);

                HtmlTableCell htcell8 = new HtmlTableCell();
                htcell8.ID = "htcell8" + ControlCounter.ToString();
                AjaxControlToolkit.AutoCompleteExtender autoItem = new AjaxControlToolkit.AutoCompleteExtender();
                autoItem.ID = LstAutoExtName[i].ToString();
                autoItem.ServiceMethod = "GetItemName";
                autoItem.MinimumPrefixLength = 1;
                autoItem.CompletionInterval = 0;
                autoItem.OnClientItemSelected = "duplicaterow";
                autoItem.CompletionListCssClass = "AutoExtender";
                autoItem.CompletionListItemCssClass = "AutoExtenderList";
                autoItem.CompletionListHighlightedItemCssClass = "AutoExtenderHighlight";
                autoItem.EnableCaching = false;
                autoItem.TargetControlID = txtItem.ID;
                htcell8.Controls.Add(autoItem);

                HtmlTableCell htcell2 = new HtmlTableCell();
                htcell2.ID = "htcell2" + ControlCounter.ToString();
                htcell2.VAlign = "Top";
                htcell2.Width = "10%";
                TextBox txtQty = new TextBox();
                txtQty.ID = LstQty[i].ToString();
                txtQty.Width = Unit.Percentage(99);
                txtQty.MaxLength = 12;
                txtQty.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
                txtQty.Attributes.Add("onblur", "EditHappen(this.id); calcQty(); calcAmt();");
                txtQty.AutoCompleteType = AutoCompleteType.Disabled;
                txtQty.CssClass = "inputnumber";
                htcell2.Controls.Add(txtQty);


                HtmlTableCell htcell3 = new HtmlTableCell();
                htcell3.ID = "htcell3" + ControlCounter.ToString();
                htcell3.VAlign = "Top";
                htcell3.Width = "15%";
                TextBox txtUnit = new TextBox();
                txtUnit.ID = LstUnit[i].ToString();
                txtUnit.Width = Unit.Percentage(99);
                txtUnit.CssClass = "input";
                txtUnit.Style["background-color"] = "lightGray";
                txtUnit.Attributes.Add("onKeyPress", "return false");
                txtUnit.AutoCompleteType = AutoCompleteType.Disabled;
                htcell3.Controls.Add(txtUnit);               

                HtmlTableCell htcell6 = new HtmlTableCell();
                htcell6.ID = "htcell6" + ControlCounter.ToString();
                htcell6.VAlign = "Top";
                htcell6.Width = "15%";
                TextBox txtRateExcTax = new TextBox();
                txtRateExcTax.ID = LstRateExcTax[i].ToString();
                txtRateExcTax.Width = Unit.Percentage(99);
                txtRateExcTax.CssClass = "inputnumber";
                txtRateExcTax.MaxLength = 10;
                //txtRateExcTax.Style["background-color"] = "lightGray";
                txtRateExcTax.Attributes.Add("onblur", "EditHappen(this.id); calcRateExcl(); calcAmt();");
                txtRateExcTax.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
                txtRateExcTax.AutoCompleteType = AutoCompleteType.Disabled;
                htcell6.Controls.Add(txtRateExcTax);


                HtmlTableCell htcell7 = new HtmlTableCell();
                htcell7.ID = "htcell7" + ControlCounter.ToString();
                htcell7.VAlign = "Top";
                htcell7.Width = "15%";
                TextBox txtAmountPayable = new TextBox();
                txtAmountPayable.ID = LstAmountPayable[i].ToString();
                txtAmountPayable.Width = Unit.Percentage(97);
                txtAmountPayable.CssClass = "inputnumber";
                txtAmountPayable.Style["background-color"] = "lightGray";
                txtAmountPayable.Attributes.Add("onKeyPress", "return false");
                txtAmountPayable.AutoCompleteType = AutoCompleteType.Disabled;
                htcell7.Controls.Add(txtAmountPayable);

                HtmlTableCell htcell9 = new HtmlTableCell();
                htcell9.ID = "htcell9" + ControlCounter.ToString();
                htcell9.Width = "10%";
                htcell9.VAlign = "Top";
                DropDownList ddlmpn = new DropDownList();
                ddlmpn.ID = LstMpn[i].ToString();
                ddlmpn.Width = Unit.Percentage(97);
                ddlmpn.CssClass = "dropdown";
                htcell9.Controls.Add(ddlmpn);
                
                htrow.Cells.Add(htcell1);//35
                htrow.Cells.Add(htcell3);//15
                htrow.Cells.Add(htcell9);//10
                htrow.Cells.Add(htcell2);//10
                htrow.Cells.Add(htcell6);//15               
                htrow.Cells.Add(htcell7);//15
                htrow.Cells.Add(htcell8);
                tblItem.Rows.Add(htrow);
            }
        }
    }
    protected void btnAddMore_Click(object sender, EventArgs e)
    {
        AddMore();
    }
    protected void AddMore()
    {
        ControlCounter++;
        Label lbl = new Label();
        lbl.ID = "lbl" + ControlCounter.ToString();
        lbl.Text = ControlCounter.ToString();
        LstList.Add(lbl.ID);
        HtmlTableRow htrow = new HtmlTableRow();
        htrow.ID = "htrow" + ControlCounter.ToString();

        HtmlTableCell htcell1 = new HtmlTableCell();
        htcell1.ID = "htcell1" + ControlCounter.ToString();
        htcell1.VAlign = "Top";
        htcell1.Width = "35%";
        TextBox txtItem = new TextBox();
        txtItem.ID = "txtItem" + ControlCounter.ToString();
        txtItem.Width = Unit.Percentage(99);
        txtItem.AutoPostBack = true;
        txtItem.CssClass = "input";
        txtItem.Attributes.Add("onPaste", "return false;");
        txtItem.TextChanged += new EventHandler(txtItem_TextChanged);
        htcell1.Controls.Add(txtItem);
        LstItemName.Add(txtItem.ID);

        HtmlTableCell htcell8 = new HtmlTableCell();
        htcell8.ID = "htcell8" + ControlCounter.ToString();
        AutoCompleteExtender autoItem = new AutoCompleteExtender();
        autoItem.ID = "AutoItem" + ControlCounter.ToString();
        autoItem.ServiceMethod = "GetItemName";
        autoItem.MinimumPrefixLength = 1;
        autoItem.CompletionInterval = 0;
        autoItem.OnClientItemSelected = "duplicaterow";
        autoItem.CompletionListCssClass = "AutoExtender";
        autoItem.CompletionListItemCssClass = "AutoExtenderList";
        autoItem.CompletionListHighlightedItemCssClass = "AutoExtenderHighlight";
        autoItem.EnableCaching = false;
        autoItem.TargetControlID = txtItem.ID;
        htcell8.Controls.Add(autoItem);
        LstAutoExtName.Add(autoItem.ID);


        HtmlTableCell htcell2 = new HtmlTableCell();
        htcell2.ID = "htcell2" + ControlCounter.ToString();
        htcell2.VAlign = "Top";
        htcell2.Width = "10%";
        TextBox txtQty = new TextBox();
        txtQty.ID = "txtQty" + ControlCounter.ToString();
        txtQty.Width = Unit.Percentage(99);
        txtQty.CssClass = "inputnumber";
        txtQty.MaxLength = 12;
        txtQty.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
        txtQty.Attributes.Add("onblur", "EditHappen(this.id); calcQty(); calcAmt();");
        txtQty.AutoCompleteType = AutoCompleteType.Disabled;
        htcell2.Controls.Add(txtQty);
        LstQty.Add(txtQty.ID);

        HtmlTableCell htcell3 = new HtmlTableCell();
        htcell3.ID = "htcell3" + ControlCounter.ToString();
        htcell3.VAlign = "Top";
        htcell3.Width = "15%";
        TextBox txtUnit = new TextBox();
        txtUnit.ID = "txtUnit" + ControlCounter.ToString();
        txtUnit.Width = Unit.Percentage(99);
        txtUnit.CssClass = "input";
        txtUnit.Style["background-color"] = "lightGray";//style="background-color:lightGray;"
        //txtUnit.Attributes.Add("onKeyPress", "return false");
        txtUnit.AutoCompleteType = AutoCompleteType.Disabled;
        htcell3.Controls.Add(txtUnit);
        LstUnit.Add(txtUnit.ID);


        HtmlTableCell htcell6 = new HtmlTableCell();
        htcell6.ID = "htcell6" + ControlCounter.ToString();
        htcell6.VAlign = "Top";
        htcell6.Width = "15%";
        TextBox txtRateExcTax = new TextBox();
        txtRateExcTax.ID = "txtRateExcTax" + ControlCounter.ToString();
        txtRateExcTax.Width = Unit.Percentage(99);
        txtRateExcTax.CssClass = "inputnumber";
        txtRateExcTax.MaxLength = 10;
        //txtRateExcTax.Style["background-color"] = "lightGray";
        txtRateExcTax.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
        txtRateExcTax.Attributes.Add("onblur", "EditHappen(this.id); calcRateExcl(); calcAmt();");
        txtRateExcTax.AutoCompleteType = AutoCompleteType.Disabled;
        htcell6.Controls.Add(txtRateExcTax);
        LstRateExcTax.Add(txtRateExcTax.ID);

        HtmlTableCell htcell7 = new HtmlTableCell();
        htcell7.ID = "htcell7" + ControlCounter.ToString();
        htcell7.VAlign = "Top";
        htcell7.Width = "15%";
        TextBox txtAmountPayable = new TextBox();
        txtAmountPayable.ID = "txtAmountPayable" + ControlCounter.ToString();
        txtAmountPayable.Width = Unit.Percentage(97);
        txtAmountPayable.CssClass = "inputnumber";
        txtAmountPayable.Style["background-color"] = "lightGray";
        txtAmountPayable.Attributes.Add("onKeyPress", "return false");
        txtAmountPayable.AutoCompleteType = AutoCompleteType.Disabled;
        htcell7.Controls.Add(txtAmountPayable);
        LstAmountPayable.Add(txtAmountPayable.ID);

        HtmlTableCell htcell9 = new HtmlTableCell();
        htcell9.ID = "htcell9" + ControlCounter.ToString();
        htcell9.Width = "10%";
        htcell9.VAlign = "Top";
        DropDownList ddlmpn = new DropDownList();
        ddlmpn.ID = "ddlmpn" + ControlCounter.ToString();
        ddlmpn.Width = Unit.Percentage(97);
        ddlmpn.CssClass = "dropdown";
        htcell9.Controls.Add(ddlmpn);
        LstMpn.Add(ddlmpn.ID);

        htrow.Cells.Add(htcell1);//35
        htrow.Cells.Add(htcell3);//15
        htrow.Cells.Add(htcell9);//10
        htrow.Cells.Add(htcell2);//10
        htrow.Cells.Add(htcell6);//15        
        htrow.Cells.Add(htcell7);//15
        htrow.Cells.Add(htcell8);
        tblItem.Rows.Add(htrow);

        ViewState["LstList"] = LstList;
        ViewState["LstItemName"] = LstItemName;
        ViewState["LstAutoExtName"] = LstAutoExtName;
        ViewState["LstQty"] = LstQty;
        ViewState["LstMpn"] = LstMpn;
        ViewState["LstUnit"] = LstUnit;
        ViewState["LstTaxRate"] = LstTaxRate;
        ViewState["LstRateExcTax"] = LstRateExcTax;
        ViewState["LstAmountPayable"] = LstAmountPayable;
        hidControl.Value = ControlCounter.ToString();
    }    
    #endregion
    //For the Page Load
    #region
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            Response.Redirect("~/SessionExpired.aspx");
        }
        else
        {
            if (Request.QueryString["Poid"] != null)
            {
                POID = Request.QueryString["Poid"].ToString().Trim('-');
            }
            else
            {
                Response.Redirect("ViewPurchaseOrder.aspx");
            }
            //For Checking the Permission of the Page according to the User.
            string Pagepermission = "select PAGE_ID,PAGE_EDIT,USERID,USERNAME as EmailID from USER_PERMISSION inner join LOGIN on USER_PERMISSION.USER_ID=LOGIN.USERID where USER_ID='" + Session["userid"].ToString() + "' and PAGE_ID=417";
            //string sqlusername = "select UserName as EmailID from Login where UserID='" + Session["userid"].ToString() + "'";
            DataTable dt = DU.getdata(Pagepermission);
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["PAGE_EDIT"].ToString() == "True")
                {
                    if (!IsPostBack)
                    {
                        LstList = new List<string>();
                        ViewState["LstList"] = LstList;
                        LstQty = new List<string>();
                        ViewState["LstQty"] = LstQty;
                        LstItemName = new List<string>();
                        ViewState["LstItemName"] = LstItemName;
                        LstAutoExtName = new List<string>();
                        ViewState["LstAutoExtName"] = LstAutoExtName;
                        LstMpn = new List<string>();
                        ViewState["LstMpn"] = LstMpn;
                        LstUnit = new List<string>();
                        ViewState["LstUnit"] = LstUnit;
                        LstTaxRate = new List<string>();
                        ViewState["LstTaxRate"] = LstTaxRate;
                        LstRateExcTax = new List<string>();
                        ViewState["LstRateExcTax"] = LstRateExcTax;
                        LstAmountPayable = new List<string>();
                        ViewState["LstAmountPayable"] = LstAmountPayable;

                        BindLocations();
                        Bind_Supplier();
                        Bind_Format(); //Bind_Saleperson();           
                        Bind_SupplierBalance();    //Bind_VATCST();
                        //Bind_DDLTaxGroup();
                        BindPurchaseOrderMain(POID.ToString());
                        BindPurchaseOrderDetails(POID.ToString());
                        Enable_TextBoxs(); Bind_VoucherNo();
                        Bind_Currency();

                        //For Creating LogFile On the Page load.
                        ip = Request.ServerVariables["REMOTE_ADDR"];
                        string PurchaseOrder = TempPoMainData + PODetails;
                        ComLog.SetPurchaseOrderLogs(Session["userid"].ToString(), Session["username"].ToString(), CommonLog.Type.ActivityLog.ToString(), PurchaseOrder, "EditPurchaseOrder.aspx", ip, System.DateTime.Now.ToString());
                    }
                    ddlFormat.Enabled = false;
                    hidemailid.Value = dt.Rows[0]["EmailID"].ToString();
                }
                else
                {
                    Response.Redirect("~/AccessDenied.aspx");
                }
            }
            else
            {
                Response.Redirect("~/AccessDenied.aspx");
            }
        } 
    }
    protected void BindPurchaseOrderMain(string Getpoid)
    {
        string paymentMode = "";
        SqlParameter[] sparam = { new SqlParameter("@POID", Getpoid.ToString()) };
        DataTable DTPOMain = DU.getdatausingprocedure("USP_GetPOMain_Details", sparam);
        if (DTPOMain.Rows.Count > 0)
        {
            //txtDate.Text = System.DateTime.Now.ToString(string.Format("dd/MM/yyyy"));
            ddlFormat.SelectedValue = DTPOMain.Rows[0]["BillFormatId"].ToString();
            DdlLocation.SelectedValue = DTPOMain.Rows[0]["DeliveryLocation"].ToString();
            ddlSupplier.SelectedValue = DTPOMain.Rows[0]["LID"].ToString();
            ddlleased.SelectedValue = DTPOMain.Rows[0]["LEASEDTYPE"].ToString();
            ddlcurrency.SelectedValue = DTPOMain.Rows[0]["currency"].ToString();
            txtvendorref.Text = DTPOMain.Rows[0]["vendorquoteref"].ToString();
            strsql = "Select * from ACC_LEDOTHERDETAILS where LID='" + DTPOMain.Rows[0]["LID"].ToString() + "'";
            DataTable DT1 = DU.getdata(strsql);
            if (DT1.Rows.Count > 0)
            {
                lblVendorCreditLimit.Text = DT1.Rows[0]["CREDITLIMIT"].ToString();
            }
            txtPrefix.Value = DTPOMain.Rows[0]["PoPrefix"].ToString();
            txtVoucher.Value = DTPOMain.Rows[0]["PoVoucherNo"].ToString();
            txtSuffix.Value = DTPOMain.Rows[0]["PoSuffix"].ToString();
            if (DTPOMain.Rows[0]["Cash_Credit"].ToString() != string.Empty)
            {
                if (DTPOMain.Rows[0]["Cash_Credit"].ToString() == "1")//for credit days
                {
                    tblowned.Style["display"] = "block";
                    tblconsigned.Style["display"] = "none";
                    radioCredit.Checked = true;
                    txtCreditDay.Text = DTPOMain.Rows[0]["CreditDay"].ToString();
                    paymentMode = "Credit " + DTPOMain.Rows[0]["CreditDay"].ToString() + " Days";
                }
                else if (DTPOMain.Rows[0]["Cash_Credit"].ToString() == "2")//for COD
                {
                    tblowned.Style["display"] = "block";
                    tblconsigned.Style["display"] = "none";
                    radioCOD.Checked = true;
                    txtCreditDay.Text = "";
                    paymentMode = "Cash On Delivery";
                }
                else if (DTPOMain.Rows[0]["Cash_Credit"].ToString() == "0")//For Advance
                {
                    tblowned.Style["display"] = "block";
                    tblconsigned.Style["display"] = "none";
                    radioCash.Checked = true;
                    txtCreditDay.Text = "";
                    paymentMode = "Advance";
                }
                else if (DTPOMain.Rows[0]["Cash_Credit"].ToString() == "3")
                {
                    tblconsigned.Style["display"] = "block";
                    tblowned.Style["display"] = "none";
                    radioFOC.Checked = true;
                    txtCreditDay.Text = "";
                    paymentMode = "Free Of Cost";
                }
            }
            txtTotalItem.Text = Convert.ToDouble(DTPOMain.Rows[0]["TotalQty"].ToString()).ToString("N0");
            txtTaxableAmt.Text = Convert.ToDouble(DTPOMain.Rows[0]["TaxableAmt"].ToString()).ToString("N5");
            txtPostTaxTotal.Text = Convert.ToDouble(DTPOMain.Rows[0]["PostTaxTotal"].ToString()).ToString("N5");
            txtRoundoff.Text = Convert.ToDouble(DTPOMain.Rows[0]["RoundOff"].ToString()).ToString("N5");
            txtGrandTotal.Text = Convert.ToDouble(DTPOMain.Rows[0]["GrandTotal"].ToString()).ToString("N2");
            txtBillAddress.Text = DTPOMain.Rows[0]["BillingAddress"].ToString().Replace("<br/>", "\r");
            txtDeliveryAdd.Text = DTPOMain.Rows[0]["DeliveryAddress"].ToString().Replace("<br/>", "\r");
            if (DTPOMain.Rows[0]["BillFormatId"].ToString() == "4")//For international
            {
                string[] delivery = DTPOMain.Rows[0]["DeliveryTerms"].ToString().Split('(');
                ddlDeliveryTerms.SelectedItem.Text = delivery[0].ToString();
                if (delivery.Length > 1)
                {
                    txtDeliveryTerms.Text = delivery[1].ToString();
                }
            }
            else
            {
                ddlDeliveryTerms.Enabled = false;
                txtDeliveryTerms.Text = DTPOMain.Rows[0]["DeliveryTerms"].ToString().Replace("<br/>", "\r");
            }

            if (DTPOMain.Rows[0]["DeliveryDate"].ToString() != string.Empty)
            {
                if (Convert.ToDateTime(DTPOMain.Rows[0]["DeliveryDate"].ToString()) == Convert.ToDateTime("1/1/1900"))
                {
                    txtDeliveryDate.Text = "";
                }
                else
                {
                    txtDeliveryDate.Text = string.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(DTPOMain.Rows[0]["DeliveryDate"].ToString()));
                }
            }
            for (int i = 0; i < RblModeDispatch.Items.Count; i++)
            {
                if (DTPOMain.Rows[0]["DeliveryMode"].ToString() == RblModeDispatch.Items[i].Text)
                {
                    RblModeDispatch.Items[i].Selected = true;
                    txtModeDispatch.Style["display"] = "none";
                    break;
                }
                if (DTPOMain.Rows[0]["DeliveryMode"].ToString() != RblModeDispatch.Items[i].Text)
                {
                    RblModeDispatch.Items[i].Selected = true;
                    txtModeDispatch.Text = DTPOMain.Rows[0]["DeliveryMode"].ToString();
                    txtModeDispatch.Style["display"] = "block";
                }
            }
            for (int j = 0; j < RblAcceptanceCriteria.Items.Count; j++)
            {
                if (DTPOMain.Rows[0]["AcceptanceCriteria"].ToString() == RblAcceptanceCriteria.Items[j].Text)
                {
                    RblAcceptanceCriteria.Items[j].Selected = true;
                    txtAcceptanceCriteria.Style["display"] = "none";
                    break;
                }
                if (DTPOMain.Rows[0]["AcceptanceCriteria"].ToString() != RblAcceptanceCriteria.Items[j].Text)
                {
                    RblAcceptanceCriteria.Items[j].Selected = true;
                    txtAcceptanceCriteria.Text = DTPOMain.Rows[0]["AcceptanceCriteria"].ToString();
                    txtAcceptanceCriteria.Style["display"] = "block";
                }
            }
            for (int k = 0; k < RblvalidityofPO.Items.Count; k++)
            {
                if (DTPOMain.Rows[0]["ValidityOfPO"].ToString() == RblvalidityofPO.Items[k].Text)
                {
                    RblvalidityofPO.Items[k].Selected = true;
                    txtvalidityofPO.Style["display"] = "none";
                    break;
                }
                if (DTPOMain.Rows[0]["ValidityOfPO"].ToString() != RblvalidityofPO.Items[k].Text)
                {
                    RblvalidityofPO.Items[k].Selected = true;
                    txtvalidityofPO.Text = DTPOMain.Rows[0]["ValidityOfPO"].ToString();
                    txtvalidityofPO.Style["display"] = "block";
                }
            }
            for (int b = 0; b < RblInsurance.Items.Count; b++)
            {
                if (DTPOMain.Rows[0]["Insurance"].ToString() == RblInsurance.Items[b].Text)
                {
                    RblInsurance.Items[b].Selected = true;
                    txtInsurance.Style["display"] = "none";
                    break;
                }
                if (DTPOMain.Rows[0]["Insurance"].ToString() != RblInsurance.Items[b].Text)
                {
                    RblInsurance.Items[b].Selected = true;
                    txtInsurance.Text = DTPOMain.Rows[0]["Insurance"].ToString();
                    txtInsurance.Style["display"] = "block";
                }
            }
            for (int f = 0; f < RBLFreight.Items.Count; f++)
            {
                if (DTPOMain.Rows[0]["Freight"].ToString() == RBLFreight.Items[f].Text)
                {
                    RBLFreight.Items[f].Selected = true;
                    txtfreight.Style["display"] = "none";
                    break;
                }
                if (DTPOMain.Rows[0]["Freight"].ToString() != RBLFreight.Items[f].Text)
                {
                    RBLFreight.Items[f].Selected = true;
                    txtfreight.Text = DTPOMain.Rows[0]["Freight"].ToString();
                    txtfreight.Style["display"] = "block";
                }
            }
            for (int g = 0; g < RblWarranty.Items.Count; g++)
            {
                if (DTPOMain.Rows[0]["Warranty"].ToString() == RblWarranty.Items[g].Text)
                {
                    RblWarranty.Items[g].Selected = true;
                    txtWarranty.Style["display"] = "none";
                    break;
                }
                if (DTPOMain.Rows[0]["Warranty"].ToString() != RblWarranty.Items[g].Text)
                {
                    RblWarranty.Items[g].Selected = true;
                    txtWarranty.Text = DTPOMain.Rows[0]["Warranty"].ToString();
                    txtWarranty.Style["display"] = "block";
                }
            }
            txtRemark.Text = DTPOMain.Rows[0]["Remarks"].ToString();
            txtfreightfwd.Text = DTPOMain.Rows[0]["FreightFWD"].ToString();
            txtimpacno.Text = DTPOMain.Rows[0]["ImportAC_No"].ToString();
            txtanyspecialcondition.Text = DTPOMain.Rows[0]["AnySpecialCondition"].ToString();
            //txtfreight.Text = DTPOMain.Rows[0]["Freight"].ToString();

            //for the Creating Log file on Page Load
            TempPoMainData = "PO.No=" + txtPrefix.Value + "/" + txtVoucher.Value + "/" + txtSuffix.Value +
            ",Supplier=" + ddlSupplier.SelectedItem + ",LeasedType=" + ddlleased.SelectedItem +
            ",DeliveryLocation=" + DdlLocation.SelectedItem + ",PaymentMode=" + paymentMode +
            ",VendorRef=" + txtvendorref.Text + ",Currency=" + ddlcurrency.SelectedItem +
            ",RoundOffAmount=" + txtRoundoff.Text + ",Mode dispatch=" + txtModeDispatch.Text +
            ",BillingAddress=" + txtBillAddress.Text + ",DeliveryAddress=" + txtDeliveryAdd.Text +
            ",TermOfDelivery=" + txtDeliveryTerms.Text + ",Handling&Packing=" + ddlhandling.SelectedItem +
            ",DeliveryDate=" + txtDeliveryDate.Text + ",Acceptance Criteria=" + txtAcceptanceCriteria.Text +
            ",Validity of PO=" + txtvalidityofPO.Text + ",Insurance=" + txtInsurance.Text + ",Warranty=" + txtWarranty.Text +
            ",Any Special Condition=" + txtanyspecialcondition.Text + ",Remarks=" + txtRemark.Text + ",Freight=" + txtfreight.Text + ",";
        }
    }
    protected void BindPurchaseOrderDetails(string Getpoid)
    {
        SqlParameter[] sparam = { new SqlParameter("@POID", Getpoid.ToString()) };
        DataTable DTPODetails = DU.getdatausingprocedure("USP_GetPODetails_Details", sparam);
        if (DTPODetails.Rows.Count > 0)
        {
            if (DTPODetails.Rows.Count > 5)
            {
                for (int i = 6; i <= DTPODetails.Rows.Count; i++)
                {
                    AddMore();
                }
            }
            for (int i = 1; i <= DTPODetails.Rows.Count; i++)
            {
                TextBox txtItem = (TextBox)tblItem.Rows[i].FindControl("txtItem" + i.ToString());
                TextBox txtUnit = (TextBox)tblItem.Rows[i].FindControl("txtUnit" + i.ToString());
                TextBox txtQty = (TextBox)tblItem.Rows[i].FindControl("txtQty" + i.ToString());
                TextBox txtRateExcTax = (TextBox)tblItem.Rows[i].FindControl("txtRateExcTax" + i.ToString());
                TextBox txtAmountPayable = (TextBox)tblItem.Rows[i].FindControl("txtAmountPayable" + i.ToString());
                HiddenField hidTaxRate = (HiddenField)tblItem.Rows[i].FindControl("hidTaxRate" + i.ToString());
                DropDownList ddlMpn = (DropDownList)tblItem.Rows[i].FindControl("ddlmpn" + i.ToString());

                string SqlMPNNO = "Select ID,MPNCODE from IVR_ITEM_MPN inner join IVR_ITEM on IVR_ITEM.ITMID=IVR_ITEM_MPN.ITEMID where IVR_ITEM.ITMCODE='" + DTPODetails.Rows[i - 1]["ITMCODE"].ToString() + "'";
                DataTable dtmpn = DU.getdata(SqlMPNNO);
                if (dtmpn.Rows.Count > 0)
                {
                    ddlMpn.DataSource = dtmpn;
                    ddlMpn.DataTextField = "MPNCODE";
                    ddlMpn.DataValueField = "ID";
                    ddlMpn.DataBind();
                    ddlMpn.Items.Insert(0, new ListItem(" ", "0"));
                    ddlMpn.SelectedItem.Text = DTPODetails.Rows[i - 1]["MPNNO"].ToString();
                }

                txtItem.Text = DTPODetails.Rows[i - 1]["ITMDESC"].ToString() + "\\" + DTPODetails.Rows[i - 1]["ITMCODE"].ToString();
                strsql = "select UOMNAME from IVR_UOM inner join IVR_ITEM on IVR_UOM.UOMID=IVR_ITEM.PRIMARY_UOMID where IVR_ITEM.ITMCODE='" + DTPODetails.Rows[i - 1]["ITMCODE"].ToString() + "'";
                DataTable DT = DU.getdata(strsql);
                if (DT.Rows.Count > 0)
                {
                    txtUnit.Text = DT.Rows[0][0].ToString();
                }
                txtQty.Text = string.Format("{0:0}", Convert.ToDecimal(DTPODetails.Rows[i - 1]["ItemQty"].ToString())).ToString();
                txtRateExcTax.Text = string.Format("{0:0.00000}", Convert.ToDecimal(DTPODetails.Rows[i - 1]["RateExclTax"].ToString())).ToString();
                txtAmountPayable.Text = string.Format("{0:0.00000}", Convert.ToDecimal(DTPODetails.Rows[i - 1]["TotalAmount"].ToString())).ToString();

                //for the Creating Log file on Page Load
                PODetails += "Item=" + txtItem.Text + ",ItemQty=" + txtQty.Text + ",RateExclTax=" + txtRateExcTax.Text + ", Amount Payable=" + txtAmountPayable.Text;
            }
        }
    }
    #endregion
    //Function for the Page which is required in the Process 
    #region
    protected void Bind_Currency()
    {
        strsql = " select * from MAS_Currency";
        DataTable dtcur = DU.getdata(strsql);
        if (dtcur.Rows.Count > 0)
        {
            ddlcurrency.DataSource = dtcur;
            ddlcurrency.DataTextField = "currency_name";
            ddlcurrency.DataValueField = "id";
            ddlcurrency.DataBind();
            ddlcurrency.Items.Insert(0, new ListItem("- Choose Currency -", "0"));
        }
    }    
    protected void Bind_VoucherNo()
    {
        string MainVoucher = "";
        string Prepix = "";
        string Suffix = "";
        string strchecksql = "select max(convert(int,PoVoucherNo)) as PoVoucherNo from ACC_POMAIN where BillFormatID=" + ddlFormat.SelectedValue + " and POID=" + POID + "";
        DataTable dtcheck = DU.getdata(strchecksql);
        if (dtcheck.Rows[0]["PoVoucherNo"].ToString() == null || dtcheck.Rows[0]["PoVoucherNo"].ToString() == string.Empty)
        {
            SqlParameter[] sparam =
                                 {
                                     new SqlParameter("@BillFormatId",ddlFormat.SelectedValue)
                                 };
            DataTable DTNum = DU.getdatausingprocedure("USP_GetPOVoucherNoFormat", sparam);
            if (DTNum.Rows.Count > 0 && DTNum.Rows[0][0].ToString() != string.Empty)
            {
                strsql = "Select * from IVR_TRANFORMATNUM where TFOID='" + ddlFormat.SelectedValue + "'";
                DataTable DT = DU.getdata(strsql);
                if (DT.Rows.Count > 0)
                {
                    if (DT.Rows[0]["NUMBERINGMETHOD"].ToString() == "True")
                    {
                        string SetZero = "";
                        int NumLength = Convert.ToInt32(DT.Rows[0]["NUMSTART"].ToString().Length);
                        int NumWidth = Convert.ToInt32(DT.Rows[0]["NUMDIGITS"].ToString());
                        int Diff = NumWidth - NumLength;
                        if (NumLength < NumWidth)
                        {
                            for (int i = 0; i < Diff; i++)
                            {
                                SetZero += "0";
                            }

                        }
                        double Povoucher = Convert.ToDouble(DTNum.Rows[0]["PoVoucherNo"].ToString());
                        MainVoucher = SetZero + (Povoucher + 1).ToString();
                        //txtVoucher.Attributes.Add("onKeyPress", "return false");
                        //txtVoucher.Attributes.Add("onKeyDown", "return false");
                    }
                    else
                    {
                        //txtVoucher.Attributes.Add("onKeyPress", "return true");
                        //txtVoucher.Attributes.Add("onKeyDown", "return true");
                    }
                    Prepix = DT.Rows[0]["NUMPREFIX"].ToString();
                    Suffix = DT.Rows[0]["NUMSUFFIX"].ToString();

                }
            }
            else
            {
                strsql = "Select * from IVR_TRANFORMATNUM where TFOID='" + ddlFormat.SelectedValue + "'";
                DataTable DT = DU.getdata(strsql);
                if (DT.Rows.Count > 0)
                {
                    if (DT.Rows[0]["NUMBERINGMETHOD"].ToString() == "True")
                    {
                        string SetZero = "";
                        int NumLength = Convert.ToInt32(DT.Rows[0]["NUMSTART"].ToString().Length);
                        int NumWidth = Convert.ToInt32(DT.Rows[0]["NUMDIGITS"].ToString());
                        int Diff = NumWidth - NumLength;
                        if (NumLength < NumWidth)
                        {
                            for (int i = 0; i < Diff; i++)
                            {
                                SetZero += "0";
                            }

                        }
                        MainVoucher = SetZero + DT.Rows[0]["NUMSTART"].ToString();
                        //txtVoucher.Attributes.Add("onKeyPress", "return false");
                        //txtVoucher.Attributes.Add("onKeyDown", "return false");
                    }
                    else
                    {
                        //txtVoucher.Attributes.Add("onKeyPress", "return true");
                        //txtVoucher.Attributes.Add("onKeyDown", "return true");
                    }
                    Prepix = DT.Rows[0]["NUMPREFIX"].ToString();
                    Suffix = DT.Rows[0]["NUMSUFFIX"].ToString();
                }
            }
            txtPrefix.Value = Prepix.ToString();
            txtVoucher.Value = MainVoucher.ToString();
            txtSuffix.Value = Suffix.ToString();
        }
    }    
    private void BindLocations()
    {
        DataTable DTLocation = DU.getdata("SELECT WHSID,WHSLOCATION from IVR_WAREHOUSE");
        DdlLocation.DataSource = DTLocation;
        DdlLocation.DataTextField = "WHSLOCATION";
        DdlLocation.DataValueField = "WHSID";
        DdlLocation.DataBind();
        DdlLocation.Items.Insert(0, new ListItem("-- Select Location --", "0"));
    }
    protected bool ValidateVoucherNo()
    {
        strsql = "select PoVoucherNo from acc_pomain where BillFormatId='" + ddlFormat.SelectedValue + "'and PoVoucherNo='" + txtVoucher.Value.Trim() + "' and POID<>'" + POID.ToString() + "'";
        DataTable DT = DU.getdata(strsql);
        if (DT.Rows.Count > 0)
        {
            lblMsg.Text = "";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Duplicate P.O. Number');", true);
            txtVoucher.Focus();
            return false;
        }
        else
        {
            return true;
        }
    }
    protected void Bind_Supplier()
    {
        strsql = "select * from ACC_LEDMAST where PGID='20' Order By LNAME ASC";
        DataTable DT = DU.getdata(strsql);
        if (DT.Rows.Count > 0)
        {
            ddlSupplier.DataSource = DT;
            ddlSupplier.DataTextField = "Lname";
            ddlSupplier.DataValueField = "LID";
            ddlSupplier.DataBind();
            ddlSupplier.Items.Insert(0, new ListItem("- Select Supplier -", "0"));
        }
    }
    protected void Bind_Format()
    {
        strsql = "Select TFOID,FORMATNAME from IVR_TRANFORMAT where TRANTYPE='8'";
        //strsql = "Select TFOID,FORMATNAME from IVR_TRANFORMAT";
        DataTable DT = DU.getdata(strsql);
        if (DT.Rows.Count > 0)
        {
            ddlFormat.DataSource = DT;
            ddlFormat.DataTextField = "FORMATNAME";
            ddlFormat.DataValueField = "TFOID";
            ddlFormat.DataBind();
            ddlFormat.Items.Insert(0, new ListItem("- Choose Format -", "0"));
        }
    }
    protected void Enable_TextBoxs()
    {
        strsql = "Select * from IVR_TRANFORMAT where TFOID='" + ddlFormat.SelectedValue + "'";
        DataTable DT = DU.getdata(strsql);
        if (DT.Rows.Count > 0)
        {
            //if (DT.Rows[0]["PREPAREDBY"].ToString() == "True")
            //{
            //    txtPreparedBy.Enabled = true;
            //    txtPreparedBy.BackColor = Color.White;
            //}
            //else
            //{
            //    txtPreparedBy.Enabled = false;
            //    txtPreparedBy.BackColor = ColorTranslator.FromHtml("#d4d0c8");
            //}
            //if (DT.Rows[0]["CHECKEDBY"].ToString() == "True")
            //{
            //    txtCheckedBy.Enabled = true;
            //    txtCheckedBy.BackColor = Color.White;
            //}
            //else
            //{
            //    txtCheckedBy.Enabled = false;
            //    txtCheckedBy.BackColor = ColorTranslator.FromHtml("#d4d0c8");
            //}
            //if (DT.Rows[0]["AUTHSIGNATORY"].ToString() == "True")
            //{
            //    txtSignatory.Enabled = true;
            //    txtSignatory.BackColor = Color.White;
            //}
            //else
            //{
            //    txtSignatory.Enabled = false;
            //    txtSignatory.BackColor = ColorTranslator.FromHtml("#d4d0c8");
            //}
            //if (DT.Rows[0]["NARRATION"].ToString() == "True")
            //{
            //    txtNarration.Enabled = true;
            //    txtNarration.BackColor = Color.White;
            //}
            //else
            //{
            //    txtNarration.Enabled = false;
            //    txtNarration.BackColor = ColorTranslator.FromHtml("#d4d0c8");
            //}
            //if (DT.Rows[0]["REMARKS"].ToString() == "True")
            //{
            //    txtRemark.Enabled = true;
            //    txtRemark.BackColor = Color.White;
            //}
            //else
            //{
            //    txtRemark.Enabled = false;
            //    txtRemark.BackColor = ColorTranslator.FromHtml("#d4d0c8");
            //}
        }
    }        
    protected void Bind_SupplierBalance()
    {
        strsql = "Select * from ACC_LEDMAST where LID='" + ddlSupplier.SelectedValue + "'";
        DataTable DT = DU.getdata(strsql);
        if (DT.Rows.Count > 0)
        {
            lblVenderOB.Text = DT.Rows[0]["ACTOPENING"].ToString();
            if (Convert.ToDouble(DT.Rows[0]["ACTOPENING"].ToString()) > 0)
            {
                lblVenderDrCr.Text = "Cr";
            }
            else
            {
                lblVenderDrCr.Text = "Dr";
            }
        }
    }
    #endregion
    //Dropdown list eventwhich is working on the Page
    #region
    protected void DDLTaxGroup_SelectedIndexChanged(object sender, EventArgs e)
    {
        
    }
    protected void ddlSupplier_SelectedIndexChanged(object sender, EventArgs e)
    {
        Bind_SupplierBalance();
    }
    protected void DdlLocation_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DdlLocation.SelectedValue != "0")
        {
            string sql = "SELECT * FROM IVR_WAREHOUSE where WHSID =" + DdlLocation.SelectedValue;
            DataTable dt = DU.getdata(sql);
            StringBuilder sb = new StringBuilder();
            sb.Append(dt.Rows[0]["WHSADD1"].ToString());
            if (!dt.Rows[0]["WHSADD2"].ToString().Equals(string.Empty))
            {
                sb.Append("\r" + dt.Rows[0]["WHSADD2"].ToString());
            }
            if (!dt.Rows[0]["WHSADD3"].ToString().Equals(string.Empty))
            {
                sb.Append("\r" + dt.Rows[0]["WHSADD3"].ToString());
            }
            if (!dt.Rows[0]["WHSADD4"].ToString().Equals(string.Empty))
            {
                sb.Append("\r" + dt.Rows[0]["WHSADD4"].ToString());
            }
            sb.Append("\r" + dt.Rows[0]["WHSCITY"].ToString());
            string state = "";
            string country = "";
            strsql = "select * from MAS_State Where StateId='" + dt.Rows[0]["WHSSTATE"].ToString() + "'";
            DataTable DTState = DU.getdata(strsql);
            if (DTState.Rows.Count > 0)
            {
                state = DTState.Rows[0]["STATENAME"].ToString();
            }
            strsql = "select * from MAS_Country Where CountryId='" + dt.Rows[0]["WHSCOUNTRY"].ToString() + "'";
            DataTable DTCountry = DU.getdata(strsql);
            if (DTCountry.Rows.Count > 0)
            {
                country = DTCountry.Rows[0]["COUNTRYNAME"].ToString();
            }
            sb.Append("," + state);
            if (!dt.Rows[0]["WHSPIN"].ToString().Equals(string.Empty))
            {
                sb.Append("-" + dt.Rows[0]["WHSPIN"].ToString());
            }
            sb.Append("," + country);
            if (!dt.Rows[0]["WHSPHONE"].ToString().Equals(string.Empty))
            {
                sb.Append("\r" + "Phone No.");
                sb.Append("-" + dt.Rows[0]["WHSPHONE"].ToString());
            }
            if (!dt.Rows[0]["WHSEMAIL"].ToString().Equals(string.Empty))
            {
                sb.Append("\r" + "Email Id");
                sb.Append("-" + dt.Rows[0]["WHSEMAIL"].ToString());
            }
            txtDeliveryAdd.Text = sb.ToString();
        }
    }
    #endregion  
    //For sending the Mail
    #region
    protected void SendEMail()
    {
        try
        {
            string Payment="";
            DataTable DtMail = DU.getdata("Select * from Acc_EmailSetting");
            if (DtMail.Rows.Count > 0)
            {
                if (radioCash.Checked == true)
                {
                    Payment = "Advance";
                }
                else if (radioCOD.Checked == true)
                {
                    Payment = "Cash On Delivery";
                }
                else if (radioCredit.Checked == true)
                {
                    Payment = txtCreditDay.Text +"Credit days";
                }
                else if (radioFOC.Checked == true)
                {
                    Payment = "Free Of Cost";
                }
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
                mail.To.Add("vishnuchit.vats@ctdi.in,dshukla@ctdi.com");
                mail.Bcc.Add("harish@digitalsolutions.co.in");
                mail.From = new System.Net.Mail.MailAddress(hidemailid.Value, DtMail.Rows[1]["MailDisplayName"].ToString().Trim());
                mail.Subject = "Dis-Account";
                mail.IsBodyHtml = true;
                mail.Body = "<table width='90%' cellpadding='0' cellspacing='0' style='font-family: Arial, Helvetica, sans-serif; font-size: small; font-weight: normal'><tr><td>Dear Sir/Madam</td></tr><tr><td>There is an Following Purchase Order Details as Follows:-</td></tr><tr><td align='center'><table style='border: 1px solid #818181; width: 60%; font-family: Verdana; font-size: 12px;'><tr style='background-color: #4D8732;'><td colspan='4' style='color: white; border: 1px solid #818181;'>Purchase Order Detail</td></tr><tr><td><b>Bill Format</b></td><td>" + ddlFormat.SelectedItem.ToString() + "</td><td><b>Supplier</b></td><td>" + ddlSupplier.SelectedItem.ToString() + "</td></tr><tr> <td><b>Leased Type</b></td><td>" + ddlleased.SelectedItem.ToString() + "</td><td><b>Deleviry Location</b></td><td>" + DdlLocation.SelectedItem.ToString() + "</td></tr><tr><td><b>Currency</b></td><td>" + ddlcurrency.SelectedItem.ToString() + "</td><td><b>Priority</b></td><td>" + DdlPriority.SelectedItem.ToString() + "</td></tr><tr><td><b>Payment Term</b></td><td>" + Payment + "</td></tr></table></td></tr><tr><td><table style='border: 1px solid #818181; width: 100%; font-family: Verdana; font-size: 12px;'><tr style='background-color: #4D8732;'><td colspan='5' style='color: white; border: 1px solid #818181;'><b>Item Detail</b></td></tr><tr><td style='border: 1px solid #818181; width: 40%;'><b>Item Name / Item Code</b></td><td style='border: 1px solid #818181; width: 10%;'><b>UOM</b></td><td style='border: 1px solid #818181; width: 10%;'><b>Qty</b></td><td style='border: 1px solid #818181; width: 10%;'><b>Rate</b></td><td style='border: 1px solid #818181; width: 15%;'><b>Amount Payable</b></td></tr>" + Body + "</table></td></tr><tr><td><table cellpadding='0' cellspacing='0'><tr><td style='border: 1px solid #818181; width: 40%;'></td><td style='border: 1px solid #818181; width: 10%;'><b>Item Total</b></td><td style='border: 1px solid #818181; width: 10%;' align='right'>" + Convert.ToDecimal(txtTotalItem.Text).ToString("N0") + "</td><td style='border: 1px solid #818181; width: 10%;'><b>Taxable Amount</b></td><td align='right' style='border: 1px solid #818181; width: 15%;'>" + Convert.ToDecimal(txtTaxableAmt.Text).ToString("N2") + "</td></tr></table></td></tr><tr><td><b>Thanks & Regards</b></td></tr></table>";
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                smtp.Host = DtMail.Rows[1]["MailHost"].ToString().Trim();
                smtp.Port = 587;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential(DtMail.Rows[1]["MailUserID"].ToString().Trim(), DtMail.Rows[1]["MailPassword"].ToString().Trim());
                smtp.EnableSsl = true;
                smtp.Send(mail);
            }
        }
        catch (Exception ex)
        {
        }
    }    
    protected void MailTextBody(string ItemName, string ItemCode, string UOM, string Qty, string Rate, string Amount)
    {
        Body += "<tr><td style='border:1px solid #818181;'>" + ItemName + "&nbsp;/&nbsp;" + ItemCode + "</td><td style='border:1px solid #818181;'>" + UOM + "</td><td style='border:1px solid #818181; text-align:right;'>" + Qty + "</td><td style='border:1px solid #818181; text-align:right;'>" + Rate + "</td><td style='border:1px solid #818181; text-align:right;'>" + Amount + "</td></tr>";
    }
    #endregion
    //For saving the Purchase order after the Editing
    #region
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {

            if (ValidateVoucherNo())
            {
                //For Updating.
                UpdatePurchaseOrderMain();
                InsertPurchaseOrderDetails();
                SendEMail();
                //For Creating LogFile On the Approved.
                ip = Request.ServerVariables["REMOTE_ADDR"];
                string PurchaseOrder = TempPoMainData + PODetails;
                ComLog.SetPurchaseOrderLogs(Session["userid"].ToString(), Session["username"].ToString(), CommonLog.Type.ActivityLog.ToString(), PurchaseOrder, "EditPurchaseOrder.aspx", ip, System.DateTime.Now.ToString());

                ScriptManager.RegisterStartupScript(this, this.GetType(), "Information", "showMsg();", true);
            }
            else
            {
                return;
            }
        }
        catch (Exception Ex)
        {
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("PurchaseOrder.aspx?View=True");
    }
    protected void UpdatePurchaseOrderMain()
    {
        string DeliveryDate = "";
        string ModeOfDispatch = "";
        string AcceptanceCriteria = "";
        string Validityofpo = "";
        string Insurance = "";
        string Warranty = "";
        string Freight = "";
        string paymentMode = "";
        string termofdelivery = "";
        int cash_credit = 0;
        if (radioCash.Checked == true)
        {
            cash_credit = 0;
            paymentMode = "Advance";
        }
        else if (radioCOD.Checked == true)
        {
            cash_credit = 2;
            paymentMode = "Cash On Delivery";
        }
        else if (radioCredit.Checked == true)
        {
            cash_credit = 1;
            if (txtCreditDay.Text == string.Empty)
            {
                txtCreditDay.Text = "0";
            }
            paymentMode = "Credit " + txtCreditDay.Text + " Days";
        }
        else if(radioFOC.Checked==true)
        {
            cash_credit = 3;
            paymentMode = "Free of Cost";
        }
        if (txtDeliveryDate.Text != "")
        {
            string[] str = txtDeliveryDate.Text.ToString().Split('/');
            DeliveryDate = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
        }
        else
        {
            DeliveryDate = null;
        }
        string RejectRemarks = "";
        if (RblModeDispatch.SelectedValue == "0")
        {
            ModeOfDispatch = txtModeDispatch.Text;
        }
        else
        {
            ModeOfDispatch = RblModeDispatch.SelectedItem.Text;
        }
        if (RblAcceptanceCriteria.SelectedValue == "0")
        {
            AcceptanceCriteria = txtAcceptanceCriteria.Text;
        }
        else
        {
            AcceptanceCriteria = RblAcceptanceCriteria.SelectedItem.Text;
        }
        if (RblvalidityofPO.SelectedValue == "0")
        {
            Validityofpo = txtvalidityofPO.Text;
        }
        else
        {
            Validityofpo = RblvalidityofPO.SelectedItem.Text;
        }
        if (RblInsurance.SelectedValue == "0")
        {
            Insurance = txtInsurance.Text;
        }
        else
        {
            Insurance = RblInsurance.SelectedItem.Text;
        }
        if (RBLFreight.SelectedValue == "0")
        {
            Freight = txtfreight.Text;
        }
        else
        {
            Freight = RBLFreight.SelectedItem.Text;
        }

        if (RblWarranty.SelectedValue == "0")
        {
            Warranty = txtWarranty.Text;
        }
        else
        {
            Warranty = RblWarranty.SelectedItem.Text;
        }
        if(ddlFormat.SelectedValue=="4")//for international
        {
            termofdelivery = ddlDeliveryTerms.SelectedItem.Text + "(" + txtDeliveryTerms.Text;
        }
        else //for domestic
        {
            termofdelivery = txtDeliveryTerms.Text;
        }
        try
        {
            SqlParameter[] sparam ={
                                        new SqlParameter ("@POID",POID.ToString()),
                                        new SqlParameter ("@BillFormatId",ddlFormat.SelectedValue),
                                        new SqlParameter ("@LID",ddlSupplier.SelectedValue ),                                       
                                        //new SqlParameter ("@PODate",Podate),                                      
                                        //new SqlParameter ("@PoPrefix",txtPrefix.Value.Trim()),
                                        //new SqlParameter ("@PoVoucherNo",txtVoucher.Value.Trim()),
                                        //new SqlParameter ("@PoSuffix",txtSuffix.Value.Trim()),
                                        new SqlParameter ("@TaxGroupId","0"),
                                        new SqlParameter ("@Cash_Credit",cash_credit),
                                        new SqlParameter ("@CreditDay",txtCreditDay.Text.Trim()), 
                                        new SqlParameter ("@TotalQty",Convert.ToDecimal(txtTotalItem.Text.Trim())),
                                        //new SqlParameter ("@PreTaxTotal",Convert.ToDecimal(txtPreTotalTax.Text.Trim())),
                                        new SqlParameter ("@PreTaxTotal",Convert.ToDecimal("0.0")),
                                        new SqlParameter ("@TaxableAmt",Convert.ToDecimal(txtTaxableAmt.Text.Trim())),
                                        new SqlParameter ("@TaxAmt",Convert.ToDecimal("0.0")),
                                        new SqlParameter ("@PostTaxTotal",Convert.ToDecimal(txtPostTaxTotal.Text.Trim())),
                                        new SqlParameter ("@RoundOff",Convert.ToDecimal(txtRoundoff.Text.Trim())),
                                        new SqlParameter ("@GrandTotal",Convert.ToDecimal(txtGrandTotal.Text.Trim())),
                                        new SqlParameter ("@BillingAddress",txtBillAddress.Text.Replace("\r","<br/>")),
                                        new SqlParameter ("@DeliveryAddress",txtDeliveryAdd.Text.Replace("\r","<br/>")),
                                        new SqlParameter ("@DeliveryTerms",termofdelivery),
                                        new SqlParameter ("@DeliveryMode",ModeOfDispatch.Trim()),
                                        new SqlParameter ("@DeliveryDate",DeliveryDate),
                                        new SqlParameter ("@AcceptanceCriteria",AcceptanceCriteria.Trim()),
                                        new SqlParameter ("@ValidityOfPO",Validityofpo.Trim()),
                                        new SqlParameter ("@Insurance",Insurance.Trim()),
                                        new SqlParameter ("@Warranty",Warranty.Trim()),
                                        new SqlParameter ("@AnySpecialCondition",txtanyspecialcondition.Text.Trim()),
                                        new SqlParameter ("@Remarks",txtRemark.Text.Trim()),                                        
                                        //new SqlParameter ("@Ename",Session["username"].ToString()),                                        
                                        new SqlParameter ("@Priority",DdlPriority.SelectedItem.Text.ToString()),
                                        new SqlParameter ("@DeliveryLocation",DdlLocation.SelectedValue),                                        
                                        new SqlParameter ("@Leasedtype",ddlleased.SelectedValue),
                                        new SqlParameter ("@Stages","1"),
                                        new SqlParameter ("@Status","1"),
                                        new SqlParameter ("@RejectRemarks",RejectRemarks),
                                        new SqlParameter ("@vendorquoteref",txtvendorref.Text),
                                        new SqlParameter ("@currency",ddlcurrency.SelectedValue),
                                        new SqlParameter ("@exchangerate","1"),
                                        new SqlParameter ("@Handling_Packing",ddlhandling.SelectedItem.ToString()),
                                        new SqlParameter ("@TaxDuties",txttaxDuties.Text),
                                        new SqlParameter ("@freight",Freight),
                                        new SqlParameter ("@ImportAcno",txtimpacno.Text),
                           };
            DU.executeprocedure("USP_ACC_Edit_Reject_POOrder_Main", sparam);
            lblMsg.Text = "Purchase Order Updated Successfully";
            TempPoMainData = "";
            TempPoMainData = "Purchase Order Approved By Manager:- PO.No=" + txtPrefix.Value + "/" + txtVoucher.Value + "/" + txtSuffix.Value +
        ",Supplier=" + ddlSupplier.SelectedItem + ",LeasedType=" + ddlleased.SelectedItem +
        ",DeliveryLocation=" + DdlLocation.SelectedItem + ",PaymentMode=" + paymentMode +
        ",VendorRef=" + txtvendorref.Text + ",Currency=" + ddlcurrency.SelectedItem +
        ",RoundOffAmount=" + txtRoundoff.Text + ",Mode dispatch=" + txtModeDispatch.Text +
        ",BillingAddress=" + txtBillAddress.Text + ",DeliveryAddress=" + txtDeliveryAdd.Text +
        ",TermOfDelivery=" + termofdelivery + ",Handling&Packing=" + ddlhandling.SelectedItem +
        ",DeliveryDate=" + txtDeliveryDate.Text + ",Acceptance Criteria=" + txtAcceptanceCriteria.Text +
        ",Validity of PO=" + txtvalidityofPO.Text + ",Insurance=" + txtInsurance.Text + ",Warranty=" + txtWarranty.Text +
        ",Any Special Condition=" + txtanyspecialcondition.Text + ",Remarks=" + txtRemark.Text + ",Freight="+Freight+",";
        }
        catch (Exception Ex)
        {
            return;
        }
    }
    protected void InsertPurchaseOrderDetails()
    {
        string TempTaxType = ""; string TempTaxtypeId = ""; string ddlmpnNo = ""; string PODetails = "";
        try
        {
            if (Request.QueryString["Poid"].ToString() != string.Empty)
            {
                strsql = "Delete From ACC_PODETAILS Where PoId='" + POID.ToString() + "'";
                DU.executesql(strsql);
                int count = Convert.ToInt32(hidControl.Value);
                for (int i = 1; i <= count; i++)
                {
                    TextBox txtItem = (TextBox)tblItem.Rows[i].FindControl("txtItem" + i.ToString());
                    TextBox txtQty = (TextBox)tblItem.Rows[i].FindControl("txtQty" + i.ToString());
                    TextBox txtRateExcTax = (TextBox)tblItem.Rows[i].FindControl("txtRateExcTax" + i.ToString());
                    TextBox txtAmountPayable = (TextBox)tblItem.Rows[i].FindControl("txtAmountPayable" + i.ToString());
                    DropDownList ddlMpn = (DropDownList)tblItem.Rows[i].FindControl("ddlmpn" + i.ToString());
                    TextBox txtUnit = (TextBox)tblItem.Rows[i].FindControl("txtUnit" + i.ToString());
                    if (ddlFormat.SelectedValue == "4")//international
                    {
                        TempTaxType = "Imported";
                        TempTaxtypeId = "22";
                    }
                    else
                    {
                        TempTaxType = "Domestic";
                        TempTaxtypeId = "0";
                    }
                    if (txtItem.Text != "")
                    {
                        if (ddlMpn.SelectedItem.ToString() == "")
                        {
                            ddlmpnNo = "0";
                        }
                        else
                        {
                            ddlmpnNo = ddlMpn.SelectedItem.ToString();
                        }
                        decimal taxAmt = 0;
                        decimal taxableAmt = 0;
                        string ItemId = "";
                        string UOMID = "";
                        string[] itemdetail = txtItem.Text.Split('\\');
                        //strsql = "Select ITMID, PRIMARY_UOMID from IVR_ITEM where ITMID='" + ddlItem.SelectedValue + "'";
                        strsql = "Select ITMID, PRIMARY_UOMID from IVR_ITEM where ITMCODE='" + itemdetail[1] + "'";
                        DataTable DT = DU.getdata(strsql);
                        {
                            if (DT.Rows.Count > 0)
                            {
                                UOMID = DT.Rows[0]["PRIMARY_UOMID"].ToString();
                                ItemId = DT.Rows[0]["ITMID"].ToString();
                            }
                        }
                        taxableAmt = Convert.ToDecimal(txtQty.Text.Trim()) * Convert.ToDecimal(txtRateExcTax.Text.Trim());
                        SqlParameter[] sparamm =
                                            {
                                            new SqlParameter ("@PoId", Request.QueryString["Poid"].ToString()),                                            
                                            new SqlParameter ("@ItemId",ItemId.ToString()),
                                            new SqlParameter ("@MPNNO",ddlmpnNo),
                                            new SqlParameter ("@UomId",UOMID.ToString()),
                                            new SqlParameter ("@ItemQty",txtQty.Text.Trim()),
                                            new SqlParameter ("@RateInclTax","0"),
                                            new SqlParameter ("@RateExclTax",txtRateExcTax.Text.Trim()),
                                            new SqlParameter ("@TaxableAmt",taxableAmt),
                                            new SqlParameter ("@TaxType",TempTaxType.ToString()),
                                            new SqlParameter ("@TaxTypeId",TempTaxtypeId.ToString()),
                                            new SqlParameter ("@TaxGroupId","0"),            
                                            new SqlParameter ("@TaxRate","0"),
                                            new SqlParameter ("@TaxAmt",taxAmt.ToString()),
                                            new SqlParameter ("@TotalAmount",txtAmountPayable.Text.Trim()),
                                            new SqlParameter ("@PurReceiveQty","0")
                                        };
                        DU.executeprocedure("USP_ACC_SavePurOrder_Details", sparamm);
                        MailTextBody(itemdetail[0], itemdetail[1], txtUnit.Text, Convert.ToDecimal(txtQty.Text).ToString(), Convert.ToDecimal(txtRateExcTax.Text).ToString(), Convert.ToDecimal(taxableAmt).ToString("N2"));
                        //For Log creation
                        PODetails += "Item=" + txtItem.Text + ",ItemQty=" + txtQty.Text + ",RateExclTax=" + txtRateExcTax.Text + ", Amount Payable=" + txtAmountPayable.Text;
                    }
                }
                lblMsg.Text = "Purchase Order Created Successfully";
                lblMsg.ForeColor = System.Drawing.Color.Green;
            }
        }
        catch (Exception Ex)
        {
            return;
        }
    }
    #endregion
}

